package com.zxlspace.java8;

import java.util.Optional;

/**
 * @ClassName Java8OptionalTest
 * @Description TODO
 * @Author zhangxiaolin@pinpianyi.com
 * @Date 2019/4/11 17:44
 * @Version 1.0
 **/
public class Java8OptionalTest {
    public static void main(String[] args) {
        Java8OptionalTest optionalTest = new Java8OptionalTest();
        Integer value1 = null;
        Integer value2 = new Integer(10);

        //Optional.ofNullable 允许传递为null的参数
        Optional<Integer> a = Optional.ofNullable(value1);

        // Optional.of - 如果传递的参数是 null，抛出异常 NullPointerException
//        Optional<Integer> a1 = Optional.of(value1);
        Optional<Integer> b = Optional.of(value2);
        System.out.println(optionalTest.sum(a, b));
    }

    public Integer sum(Optional<Integer> a, Optional<Integer> b) {
        //Optional.isPresent() - 判断值是否存在
        System.out.println("判断第一个值是否能存在：" + a.isPresent());
        System.out.println("判断第二个值是否能存在：" + b.isPresent());

        //Optional.orElse() - 如果值存在，返回他，不存在返回默认值
        Integer value1 = a.orElse(new Integer(0));

        //Optional.get() - 获取值，值必须存在
        Integer value2 = b.get();
        return value1 + value2;
    }
}
